using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Text;

namespace System
{
	public static class IntptrExtension
	{
		public static T ByteToStructure<T>(this byte[] dataBuffer)
		{
			object structure = null;
			int num = Marshal.SizeOf(typeof(T));
			IntPtr intPtr = Marshal.AllocHGlobal(num);
			try
			{
				Marshal.Copy(dataBuffer, 0, intPtr, num);
				structure = Marshal.PtrToStructure(intPtr, typeof(T));
			}
			finally
			{
				Marshal.FreeHGlobal(intPtr);
			}
			return (T)structure;
		}

		public static IntPtr Increment<T>(this IntPtr intptr)
		{
			IntPtr num = (IntPtr)(intptr.ToInt32() + Marshal.SizeOf(typeof(T)));
			return num;
		}

		public static T[] IntPtrToStructs<T>(this IntPtr intptr, int count)
		where T : struct
		{
			T[] tArray = new T[count];
			T structure = default(T);
			for (int i = 0; i < count; i++)
			{
				structure = (T)Marshal.PtrToStructure(intptr, typeof(T));
				tArray[i] = structure;
				intptr = (IntPtr)(Marshal.SizeOf(structure) + intptr.ToInt32());
			}
			return tArray;
		}

		public static byte[] Ptr2Bytes(this IntPtr ptr)
		{
			return PtrtoByteArray(ptr);
		}

		private static unsafe byte[] PtrtoByteArray(this IntPtr ptr)
		{
			byte[] array;
			if (!(ptr == IntPtr.Zero))
			{
				List<byte> nums = new List<byte>();
				int num = 0;
				byte* numPointer = (byte*)((void*)ptr);
				while (true)
				{
					if ((*numPointer == 0 ? true : num >= 10000000))
					{
						break;
					}
					nums.Add(*numPointer);
					num++;
					numPointer++;
				}
				array = nums.ToArray();
			}
			else
			{
				array = new byte[0];
			}
			return array;
		}

		public static string ToAnsiString(this IntPtr intPtr)
		{
			string str = Encoding.Default.GetString(Encoding.Convert(Encoding.UTF8, Encoding.Default, PtrtoByteArray(intPtr)));
			return str;
		}

		public static string ToGB2312String(this IntPtr intPtr)
		{
			return Encoding.Default.GetString(PtrtoByteArray(intPtr));
		}

		public static T ToStruct<T>(this IntPtr intptr)
		where T : struct
		{
			T t;
			t = (!intptr.Equals(IntPtr.Zero) ? (T)Marshal.PtrToStructure(intptr, typeof(T)) : default(T));
			return t;
		}

		public static string ToUTF8String(this IntPtr intPtr)
		{
			return Encoding.UTF8.GetString(PtrtoByteArray(intPtr));
		}
	}
}